#coding: utf-8
# 此文件在GAE上已经没使用。

import re,os
from email.MIMEText import MIMEText
from email.MIMEImage import MIMEImage
from email.MIMEMultipart import MIMEMultipart
from email.mime.application import MIMEApplication

def upload_file(request):
    '''
    上传附件，如果有，上传成功返回完整路径。不成为返回None
    '''
    from fckeditor.connector.actions import file_upload
    abs_path = os.path.dirname(__file__) + r"/temp/"
    try:
        status, filename = file_upload(request, abs_path)
        if filename == None:
            return None
    except Exception, e:
        print e
        return None

    return abs_path + filename
#end upload_file()

def deal_attach_file(htmlText, AttachFilePath):
    '''
    处理附图与附件，成功返回 (new_htmlText, MIMEImage[]，MIMEApplication) 两个对像，否刚返回 (htmlText, None, None)
    注：附件只有一个，而附图可能有多个
    '''

    list_mime_images = [] #作返回值 
    mime_app = None       #作返回值
    
    img_re = re.compile(r'''<img\s.*?\s?src\s*=\s*['|"]?([^\s'"]+).*?>''', re.I)
    img_path_list = img_re.findall(htmlText)
    
    if img_path_list.__len__() >= 1:
        dirname = os.path.dirname(__file__)
        nImgID = 1
        for strImg in img_path_list:
            if strImg.startswith("/uploads/"): #是用户上传的
                ImgPath = dirname + strImg
                try:
                    fp = open(ImgPath, 'rb')
                    mineImage = MIMEImage(fp.read())
                    strID = "Img%d" % nImgID
                    nImgID += 1
                    mineImage.add_header('Content-ID', strID)
                    strID = "cid:%s" % strID
                    htmlText = htmlText.replace(strImg, strID) # 对文本进行替换
                    list_mime_images.append(mineImage) # 加入到返回值中
                    fp.close()
                except Exception, e:
                    print e
                    
    # 处理附件
    if (AttachFilePath):
        try:
            fp = open(AttachFilePath, 'rb')
            attachmentFile = MIMEApplication(fp.read())
            fp.close()
            attachmentFile.add_header('content-disposition', 'attachment', filename=os.path.basename(AttachFilePath.encode("utf-8")))
            mime_app = attachmentFile
            os.remove(AttachFilePath) # 使用完后删除附件
        except Exception, e:
            print e
            pass
    return (htmlText, list_mime_images, mime_app)
#end deal_attach_file()

def make_MIMEMultipart(strFrom, strTo, subject, htmlText, AttachFile_Mine_imagelist, AttachFile_Mime_app):
    '''生成 MIME 邮件格式，并返回，即sendmail的第三个参数'''

    # 设定root信息,基本信息
    msgRoot = MIMEMultipart('related')
    msgRoot['Subject'] = subject
    msgRoot['From'] = strFrom
    msgRoot['To'] = strTo
    msgRoot.preamble = 'This is a multi-part message in MIME format.'

    # Encapsulate the plain and HTML versions of the message body in an
    # 'alternative' part, so message agents can decide which they want to display.
    msgAlternative = MIMEMultipart('alternative')
    msgRoot.attach(msgAlternative)

    #处理上传的图片
    if AttachFile_Mine_imagelist:
        for img in AttachFile_Mine_imagelist:
            msgRoot.attach(img)
            
    if AttachFile_Mime_app:  
        msgRoot.attach(AttachFile_Mime_app)

    #设定HTML信息
    msgText = MIMEText(htmlText, 'html', 'utf-8')
    msgAlternative.attach(msgText)

    return msgRoot
#end make_MIMEMultipart()
